package com.wsc.config;

import com.wsc.mapper.UserMapper;
import com.wsc.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *  自定义的 Realm 对象
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.err.println(" 执行了 ---------- 授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前的 Subject
        Subject subject = SecurityUtils.getSubject();
        // 从 Principal 中得到 User 对象
        User currentUser = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.err.println(" 执行了 ---------- 认证");
       /* String account = "van";
        String password = "bili";*/

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        User user = userMapper.getByName(token.getUsername());
        // 验证用户名

        if(!token.getUsername().equals(user.getName())){ // 抛出异常 UnknownAccountException
            return null;
        }

        //密码识别  params1: 把 user 放到 Principal 中
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }
}
